package main

import (
	"context"
	"deployment-service/config"
	"deployment-service/middlewares"
	"deployment-service/routes"
	_ "fmt"
	"github.com/apex/log"
	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
	"net"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

func main() {
	app := gin.New()
	app.Use(gin.Logger(), gin.Recovery())

	// 初始化配置
	if err := config.InitConfig(""); err != nil {
		log.Error("init config error:" + err.Error())
		panic(err)
	}
	log.Info("initialized config successfully")

	app.Use(middlewares.CORSMiddleware())
	jenkinsGroup := app.Group("/jenkins")
	{
		jenkinsGroup.POST("/getJenkinsJob", routes.GetJenkinsJob)       // 获取jenkins的job信息
		jenkinsGroup.POST("/getJenkinsJobLastBuild", routes.GetJenkinsJobLastBuild) // 获取job最后编译结果
		jenkinsGroup.POST("/createJenkinsJob", routes.CreateJenkinsJob) // 创建job
		jenkinsGroup.POST("/buildJenkinsJob", routes.BuildJenkinsJob)   // 构建job
		jenkinsGroup.POST("/getJenkinsBuildResult", routes.GetJenkinsBuildResult) // 获取job编译结果
		jenkinsGroup.POST("/getJenkinsBuildLog", routes.GetJenkinsBuildLog) // 获取job编译日志
	}

	k8sGroup := app.Group("/k8s")
	{
		k8sGroup.POST("/deploy", routes.Deploy)              // 部署
		k8sGroup.POST("/healthCheck", routes.HealthCheck)    // 心跳检测
		k8sGroup.POST("/getDeploymentLog", routes.GetDeploymentLog) // 获取日志
		k8sGroup.POST("/getDeployments", routes.GetDeployments)
		k8sGroup.POST("/getReplicaSet", routes.GetReplicaSet)
		k8sGroup.POST("/getPods", routes.GetPods)
		k8sGroup.POST("/getPodMetrics", routes.GetPodMetrics)
		k8sGroup.POST("/getPodLog", routes.GetPodLog)
		k8sGroup.POST("/rollback", routes.RollbackRevision)
	}

	rootGroup := app.Group("/")
	{
		rootGroup.GET("/", routes.Info)
	}

	// 运行服务器
	host := viper.GetString("server.host")
	port := viper.GetString("server.port")
	address := net.JoinHostPort(host, port)
	srv := &http.Server{
		Handler: app,
		Addr:    address,
	}
	go func() {
		if err := srv.ListenAndServe(); err != nil {
			if err != http.ErrServerClosed {
				log.Error("run server error:" + err.Error())
			} else {
				log.Info("server graceful down")
			}
		}
	}()
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	ctx2, cancel := context.WithTimeout(context.Background(), 20*time.Second)
	defer cancel()
	if err := srv.Shutdown(ctx2); err != nil {
		log.Error("run server error:" + err.Error())
	}
}
